<template>
	<view class="share-page">
		<view class="share-page-box msg-box" v-if="!show"
			:style="{width: canvasWidth + 'px', height: screenHeight + 'px' }">
			{{msg}}
		</view>
		<view class="share-page-box" id="box" v-else
			:style="{width: canvasWidth + 'px', height: screenHeight+'px',overflowY:'auto'}">
			<!-- <image v-if="imgShow" :src="compPct" :style="{width: canvasWidth + 'px' ,height: canvasHeight+'px'}"></image> -->

			<!-- 			<view  v-if="imgShow">
				<image :src="imgUrl" :style="{width: canvasWidth + 'px' ,height: canvasHeight+'px'}"></image>
				
			</view> -->
			<view>
				<wxml-to-canvas class="widget" :width="canvasWidth" :height="canvasHeight"></wxml-to-canvas>
				<wxml-to-canvas v-for="(item,index) in listMsg" :key="index" :class="'widget'+index"
					:width="canvasWidth" :height="item.height"></wxml-to-canvas>
				<wxml-to-canvas class="widgetBtm" :width="canvasWidth" :height="screenWidth * 0.2"></wxml-to-canvas>

			</view>
		</view>

		<view class="share-page-btn">
			<u-button @click="extraImage" :disabled="submitBtnLoading" :loading="submitBtnLoading" size="large"
				type="success" loadingText="图片生成中">保存图片</u-button>
		</view>

	</view>
</template>
<script>
	const {
		wxml0,
		wxml1,
		wxml,
		style
	} = require('./DomData.js')
	import {
		baseURL,
		download
	} from '@/utils/util.js'
	import {
		getAppletQRCode,
		shareByPicture,
		compositePicture
	} from "@/apis/index.js"
	import productTopImg from '../../static/detail/productTitleBg.png'
	import productTopImg2 from '../../static/detail/titleBg.png'
	import titleBgImg from '../../static/detail/bottom.png'
	import prod1Img from '../../static/detail/prod1.png'
	import prod2Img from '../../static/detail/prod2.png'
	import prod3Img from '../../static/detail/prod3.png'
	import prod4Img from '../../static/detail/prod4.png'
	import prod5Img from '../../static/detail/prod5.png'
	import prod8Img from '../../static/detail/prod8.png'

	import titleBgImg2 from '../../static/detail/bottom2.png'
	import scheme0Img from '../../static/detail/scheme0.png'
	import scheme1Img from '../../static/detail/scheme1.png'
	import scheme2Img from '../../static/detail/scheme2.png'
	import scheme3Img from '../../static/detail/scheme3.png'

	// import changjingBgImg from '../../static/detail/changjing.png'

	// import tapBgImg from '../../static/detail/top_b_2.png' // 方案top 背景
	// import tapBgImg2 from '../../static/detail/top_b_8.png' // 产品top 背景
import { downloadBkPic } from '../../utils/util.js'

	export default {
		name: '',
		data() {
			return {
				productTopImg,
				titleBgImg,
				titleBgImg2,
				prod1Img,
				prod2Img,
				prod3Img,
				prod4Img,
				prod5Img,
				prod8Img,
				scheme0Img,
				scheme1Img,
				scheme2Img,
				scheme3Img,
				// changjingBgImg,
				tapBgImg: '',
				imgUrl: [], // 多个canvas生成的图片arr
				imgUrl2: [], // 防止watch imgUrl过长 伴生的 无实际作用

				show: false, // 是否显示canvas
				imgShow: false, // 展示生成的图片
				canvasWidth: 320, // 默认canvas宽高
				canvasHeight: 240,

				screenHeight: 480, // 页面展示生成图片高度
				screenWidth: null, // 设备宽度
				screenScale: 1,
				name: '',
				pic: '',
				chapter1: '',
				chapter2: '',
				widget: null,
				widgetBtm: null,
				msg: '加载中，请稍等...', // 提示语
				listMsg: [],
				listMsg1: [],
				compPct: '',
				submitBtnLoading: false,
				sharePageType: '',
				businessId: '',

			}
		},
		onLoad(options) {
			console.log('options', options);

			// this.pic = ``
			this.sharePageType = options.type
			if (this.sharePageType == 1) { // 产品
				// this.tapBgImg = tapBgImg2
				this.tapBgImg = downloadBkPic('top_b_8')
				this.productTopImg = productTopImg
			} else { // 方案
				this.tapBgImg = downloadBkPic('top_b_2')
				this.productTopImg = productTopImg2
			}
			this.getPageData()

			this.businessId = options.id
			this.name = uni.getStorageSync('pageTitle') || '邮储银行金融易企典'


		},

		watch: {
			imgUrl2: {
				handler(newVal, oldVal) {
					// console.log(newVal,this.listMsg)
					if (newVal.length == this.listMsg.length + 2) {
						const ImgArrs = []
						this.imgUrl.sort((a, b) => {
							return a.idx - b.idx
						})
						this.imgUrl.forEach(item => {
							ImgArrs.push(item.val)
						})
						compositePicture(ImgArrs).then(roo => {
							if (roo.code == '00000000') {
								this.compPct = roo.data
							}
						})
					}

				},
				deep: true,
				immediate: true
			}
		},

		onReady() {
			this.imgUrl = []
			this.imgUrl2 = []
			this.compPct = ''
			new Promise((resolve) => {
				const params = {
					page: this.sharePageType == 1 ? 'pages/product/productDetail' :
						'pages/scheme/schemeDetail',
					shareVO: {
						userId: uni.getStorageSync('userMsg').userId,
						businessId: this.businessId,
						businessType: this.sharePageType,
					}
				}
				shareByPicture(params).then(res => {
					if (res.code == '00000000') {
						this.pic =
							download(res.data)
						// this.pic = 'https://pic1.zhimg.com/80/v2-58fe538a59f870407b1435bfd45893ed_720w.jpeg'
						console.log(this.pic, 123123)
						resolve()
					}
				})
			}).then(() => {
				// 获取设备信息
				wx.getSystemInfo({
					success: (res) => {
						this.screenWidth = res.screenWidth / 375 * 375
						this.screenScale = res.screenWidth / 375
						this.screenHeight = res.windowHeight * 0.85
						this.canvasWidth = this.screenWidth * 0.94
						this.show = true
						wx.showLoading({
							title: '海报生成中...'
						})
						setTimeout(() => {
							this.widgetBtm = this.selectComponent('.widgetBtm')
							const _wxmlBtm = wxml1(this.name, this.pic)
							const _styleBtm = style(this.screenScale, this.screenWidth, this
								.canvasWidth, this
								.canvasHeight, this.listMsg1)
							const pBtm = this.widgetBtm.renderToCanvas({
								wxml: _wxmlBtm,
								style: _styleBtm
							})
							pBtm.then(re => {
								const p2 = this.widgetBtm.canvasToTempFilePath()
								p2.then(r => {
									let imgbase64 = uni.getFileSystemManager()
										.readFile({
											filePath: r
												.tempFilePath, //选择图片返回的相对路径
											encoding: 'base64', //编码格式
											success: ro => { //成功的回调
												// console.log(ro.data)
												this.imgUrl.push({
													idx: 100,
													val: ro
														.data
												})
												this.imgUrl2.push({
													idx: 100
												})

											}
										})
									// arr.push(imgbase64)
								})
							})

							this.widget = this.selectComponent('.widget')
							const _wxml = wxml0(this.name, downloadBkPic('top_b_2'))
							const _style = style(this.screenScale, this.screenWidth, this
								.canvasWidth, this
								.canvasHeight, this.listMsg1)
							const p = this.widget.renderToCanvas({
								wxml: _wxml,
								style: _style
							})
							p.then((re) => {
								console.log('海报生成成功');
								const p2 = this.widget.canvasToTempFilePath()
								p2.then(r => {
									let imgbase64 = uni.getFileSystemManager()
										.readFile({
											filePath: r
												.tempFilePath, //选择图片返回的相对路径
											encoding: 'base64', //编码格式
											success: ro => { //成功的回调
												// console.log(ro.data)
												this.imgUrl.push({
													idx: 1,
													val: ro
														.data
												})
												this.imgUrl2.push({
													idx: 1
												})

											}
										})
									// arr.push(imgbase64)
								})
								wx.hideLoading()
								// this.container = res
							}).catch((err) => {
								console.log('生成失败', this.pic)
								wx.showToast({
									title: err,
									icon: 'none',
									duration: 8000
								})
							})

							for (let i = 0; i < this.listMsg.length; i++) {

								this.renderToCanvas(i, this.listMsg[i])

							}

						}, 1000)
					}
				});
			})
		},
		methods: {
			getPageData() {
				// 数字容器宽度 动态设置
				const shareMsg = uni.getStorageSync('shareMsg')
				// let platform = 'ios'
				// uni.getSystemInfo({
				// 	success: (res) => {
				// 		platform = res.platform
				// 	}
				// })
				for (let item of shareMsg) {
					item.titleBgImg = this.titleBgImg
					if (item.name == '介绍') {
						item.height = item.height + 36
						item.topBgImg = this.productTopImg
					} else if (item.name == '适用对象') {
						item.height = item.height + 60
						item.iconImg = this.prod1Img
					} else if (item.name == '产品优势') {
						item.height = item.height + 60
						item.iconImg = this.prod2Img
					} else if (item.name == '服务案例') {
						item.height = item.height + 120
						item.iconImg = this.prod3Img
					} else if (item.name == '办理流程') {
						item.height = item.height + 60
						item.iconImg = this.prod4Img
					} else if (item.name == '办理材料') {
						item.height = item.height + 60
						item.iconImg = this.prod5Img
					} else if (item.name == '客户痛点') {
						item.height = item.height + 64
						item.iconImg = this.scheme1Img
						item.titleBgImg = this.titleBgImg2

					} else if (item.name == '解决方案') {
						item.height = item.height + 10 + (item.val.length * 18)
						// if (platform == 'ios') {
						// 	item.height = item.height + 10 + (item.val.length * 18)
						// } else {
						// 	item.height = item.height + 10 + (item.val.length * 20)
						// }
						item.iconImg = this.scheme2Img
						item.titleBgImg = this.titleBgImg2

					} else if (item.name == '方案优势') {
						item.height = item.height + 60
						item.iconImg = this.scheme3Img
						item.titleBgImg = this.titleBgImg2

					} else if (item.name == '适用场景') {
						item.height = item.height + 60
						item.iconImg = this.scheme0Img
						item.titleBgImg = this.titleBgImg2
						// item.bgImg = this.changjingBgImg

					} else if (item.name == '功能介绍') {
						item.height = item.height + 60
						item.iconImg = this.prod8Img
					}
				}
				this.listMsg = shareMsg
			},


			// wxml 转 canvas
			renderToCanvas(idx, it) {

				const widget = this.selectComponent(`.widget${idx}`)
				const _wxml = wxml(this.sharePageType, it)
				const _style = style(this.screenScale, this.screenWidth, this.canvasWidth, it.height, it)
				const p = widget.renderToCanvas({
					wxml: _wxml,
					style: _style
				})
				p.then((res) => {
					const p2 = widget.canvasToTempFilePath()
					p2.then(re => {

						let imgbase64 = uni.getFileSystemManager().readFile({
							filePath: re.tempFilePath, //选择图片返回的相对路径
							encoding: 'base64', //编码格式
							success: r => { //成功的回调
								// console.log('data:image/png;base64,' + r.data)
								this.imgUrl.push({
									idx: idx + 2,
									val: r.data
								})
								this.imgUrl2.push({
									idx: idx + 2
								})
							}
						})
						// console.log(this.imgUrl,1111)
					})


					wx.hideLoading()
				}).catch((err) => {
					console.log('生成失败', this.pic)
					wx.showToast({
						title: err,
						icon: 'none',
						duration: 8000
					})
				})


			},
			// 保存到朋友圈
			extraImage() {
				if (!this.show) {
					wx.showToast({
						title: '海报生成失败，无法分享',
						icon: 'none'
					})
					return
				}
				this.submitBtnLoading = true
				setTimeout(() => {
					if (!this.compPct) {
						this.extraImage()
					} else {
						this.submitBtnLoading = false
						// const p2 = this.widget.canvasToTempFilePath()
						const that = this;
						//获取文件管理器对象
						var fsm = wx.getFileSystemManager();
						var filepath = wx.env.USER_DATA_PATH + '/test.png'
						fsm.writeFile({
							filePath: filepath,
							data: that.compPct,
							encoding: 'base64',
							success(res) {
								let path = filepath
								wx.getSetting({
									success: res => {
										// 非初始化且未授权的情况，需要再次弹窗提示授权
										if (res.authSetting['scope.writePhotosAlbum'] !=
											undefined && res
											.authSetting['scope.writePhotosAlbum'] != true) {
											wx.showModal({
												title: '是否授权相册权限',
												content: '需要获取相册权限，请确认授权，否则无法使用相关功能',
												success: re => {
													if (re.confirm) {
														wx.openSetting({
															success: dataAu => {
																if (dataAu
																	.authSetting[
																		"scope.writePhotosAlbum"
																	] ==
																	true
																) {
																	wx.showToast({
																		title: '授权成功',
																		icon: 'none',
																		duration: 1000
																	});
																	that.saveIMg(
																		path
																	);
																} else {
																	wx.showToast({
																		title: '授权失败',
																		icon: 'success',
																		duration: 1000
																	});
																}
															}
														});
													}
												}
											});
										} else {
											// 初始化且未授权，系统默认会弹窗提示授权
											// 非初始化且已授权，也会进入这里
											that.saveIMg(path);
										}
									}
								});

							},
							fail(err) {
								console.log('ERROR');
								wx.showToast({
									title: '失败，请稍后重试',
									icon: 'none',
									duration: 8000
								})
							},
						});
					}
				}, 500)


			},
			// 保存到相册
			async saveIMg(tempFilePath) {
				wx.saveImageToPhotosAlbum({
					filePath: tempFilePath,
					success: async (res) => {
						wx.showModal({
							content: '图片已保存，分享给好友吧！',
							showCancel: false,
							confirmText: '好的',
							confirmColor: '#333',
							success: function(res) {
								wx.navigateBack({
									//返回
									delta: 1
								});
							},
							fail: function(res) {
								console.log('res', res);
							}
						});
					},

					fail: function(res) {
						wx.showToast({
							title: '您取消了授权',
							icon: 'none',
							duration: 2000
						})
					}
				});
			}
		}
	}
</script>
<style lang="scss" scoped>
	.share-page {
		background: #fff;
		position: relative;
		overflow: hidden;
		min-height: 100vh;

		.msg-box {
			display: flex;
			align-items: center;
			text-align: center;
			justify-content: center;
		}

		.share-page-box {
			margin: 40rpx auto;
			position: relative;
			overflow: hidden;
			box-shadow: 0rpx 6rpx 20rpx 6rpx rgba(0, 0, 0, 0.2);
		}

		.share-page-btn {
			margin: 0 auto;
			width: 94%;

			button {
				color: #303133;
				background-color: #67C23A;
				border-color: #67C23A;
				border-radius: 80rpx;
				font-size: 32rpx;
				height: 80rpx;
				line-height: 80rpx;
			}

			img {
				width: 100%;
				height: 100%;
			}
		}
	}
</style>